/*
 * 官网地站:http://www.ShareSDK.cn
 * 技术支持QQ: 4006852216
 * 官方微信:ShareSDK   （如果发布新版本的话，我们将会第一时间通过微信将版本更新内容推送给您。如果使用过程中有任何问题，也可以通过微信与我们取得联系，我们将会在24小时内给予回复）
 *
 * Copyright (c) 2013年 ShareSDK.cn. All rights reserved.
 */

package cn.sharesdk.onekeyshare;

import cn.sharesdk.demo.R;
import cn.sharesdk.demo.util.Ad;

import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Message;
import android.os.Handler.Callback;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.FakeActivity;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.utils.UIHandler;

/** 执行图文分享的页面，此页面不支持微信平台的分享 */
public class EditPage extends FakeActivity implements OnClickListener,
		TextWatcher, Callback, PlatformActionListener {
	private static final String TAG = "EditPage";
	private static final int MAX_TEXT_COUNT = 140;
	private static final int MSG_PLATFORM_LIST_GOT = 10;
	private static final int MSG_TOAST = 20;
	private static final int SHARE_SUCCESS = 2;
	private static final int SHARE_FAILED = 3;
	private static final int SHARE_CANCEL = 4;
	private static final int AUTHORE_CANCEL = 5;
	private static final int AUTHORE_SUCCESS = 6;
	private static final int AUTHORE_FAILED = 7;
	private String platName;
	private Platform platform;
	private HashMap<String, Object> reqData;
	private OnekeyShare parent;
	private Button btBack;
	private Button btShare;
	private static Button btAuthorize;
	private View editpage;
	private TextView tvShareTo;
	// 字数计算器
	private TextView tvCounter;
	// 文本编辑框
	private EditText etContent;
	// 输入区域的图片
	private Bitmap image;
	private ImageView ivShareImage;
	// at好友
	private TextView tvAtFriends;
	// 设置显示模式为Dialog模式
	private boolean dialogMode;

	public void setShareData(HashMap<String, Object> data) {
		reqData = data;
	}

	public void setParent(OnekeyShare parent) {
		this.parent = parent;
	}

	/** 设置显示模式为Dialog模式 */
	public void setDialogMode() {
		dialogMode = true;
	}

	public void setActivity(Activity activity) {
		super.setActivity(activity);
		if (dialogMode) {
			activity.setTheme(android.R.style.Theme_Dialog);
			activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
		}
	}

	public void onCreate() {
		if (reqData == null) {
			finish();
			return;
		}
		platName = String.valueOf(reqData.get("platform"));
		platform = ShareSDK.getPlatform(getContext(), platName);
		UIHandler.prepare();
		initPageView();
		activity.setContentView(editpage);
		
		onTextChanged(etContent.getText(), 0, etContent.length(), 0);
		checkAtMth(String.valueOf(reqData.get("platform")));
//		parent.setCallback(this);
		platform.setPlatformActionListener(this);
	}

	private void initPageView() {
		LayoutInflater inflator = LayoutInflater.from(getContext());
		editpage = inflator.inflate(R.layout.edit_page, null);

		// 标题栏
		btBack = (Button) editpage.findViewById(R.id.bt_back);
		btBack.setOnClickListener(this);
		btShare = (Button) editpage.findViewById(R.id.bt_share);
		btShare.setOnClickListener(this);
		// 文字输入区域
		etContent = (EditText) editpage.findViewById(R.id.et_content);
		etContent.setText(String.valueOf(reqData.get("text")));
		etContent.addTextChangedListener(this);
		// 字数统计
		tvCounter = (TextView) editpage.findViewById(R.id.tv_counter);
		// 输入区域的图片
		ivShareImage = (ImageView) editpage.findViewById(R.id.iv_share_iamge);
		image = cn.sharesdk.framework.utils.R.getBitmap(String.valueOf(reqData
				.get("imagePath")));
		ivShareImage.setImageBitmap(image);
		ivShareImage.setOnClickListener(this);
		// at好友
		tvAtFriends = (TextView) editpage.findViewById(R.id.tv_at_friends);
		tvAtFriends.setOnClickListener(this);

		tvShareTo = (TextView) editpage.findViewById(R.id.tv_share_to);
		String text = getContext().getString(R.string.share_to);
		tvShareTo.setText(text + ":"
				+ getName(String.valueOf(reqData.get("platform"))));

		btAuthorize = (Button) editpage.findViewById(R.id.do_authorize);
		btAuthorize.setOnClickListener(this);
	}

	// 进新浪微博、腾讯微博、Facebook和Twitter支持At功能
	private void checkAtMth(String platform) {
		// 为了减短代码的长度，增强可读性，这里将代码拆分
		tvAtFriends.setVisibility(View.GONE);
		if ("SinaWeibo".equals(platform) || "TencentWeibo".equals(platform)) {
			tvAtFriends.setVisibility(View.VISIBLE);
		}
		if ("Facebook".equals(platform) || "Twitter".equals(platform)) {
			tvAtFriends.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 
	 * @param plat
	 * @return true已授权,其他false
	 */
	private boolean checkAuthorization(Platform plat) {
		if (plat.isValid()) {
			String text = getContext().getResources().getString(
					R.string.remove_authorize);
			btAuthorize.setText(text);
			return true;
		} else {
			String text = getContext().getResources().getString(
					R.string.authorize);
			btAuthorize.setText(text);
			return false;
		}
	}

	private String getName(String platform) {
		if (platform == null) {
			return "";
		}

		int resId = cn.sharesdk.framework.utils.R.getStringRes(getContext(),
				platform);
		return getContext().getString(resId);
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.bt_share:
			doShare();
			break;
		case R.id.bt_back:
			finish();
			break;
		case R.id.tv_at_friends:
			doAtFriends();
			break;
		case R.id.do_authorize:
			doAuthorize();
			break;
		case R.id.iv_share_iamge:
			showImage();
			break;

		default:
			break;
		}
	}

	/** 查看图片 */
	private void showImage() {
		if (image != null && !image.isRecycled()) {
			PicViewer pv = new PicViewer();
			pv.setImageBitmap(image);
			pv.show(activity, null);
		}
		return;

	}

	@Override
	public void onResume() {
		super.onResume();
		checkAuthorization(platform);

	}

	/**
	 * 授权处理
	 */
	private void doAuthorize() {
//		platform.setPlatformActionListener(this);
		if (checkAuthorization(platform)) {
			platform.removeAccount();
			String text = getContext().getString(R.string.remove_authorize);
			Toast.makeText(getContext(), text, 0).show();
		} else {
			platform.authorize();
		}
		checkAuthorization(platform);
	}

	/**
	 * 执行关注好友
	 */
	private void doAtFriends() {
		FollowList subPage = new FollowList();
		String platform = String.valueOf(reqData.get("platform"));
		subPage.setPlatform(ShareSDK.getPlatform(activity, platform));
		subPage.setBackPage(this);
		subPage.show(activity, null);
		return;
	}

	/**
	 * 执行分享
	 */
	private void doShare() {
		String imagePath = String.valueOf(reqData.get("imagePath"));
		String text = etContent.getText().toString();
		reqData.put("text", text);
		reqData.put("imagePath", imagePath);
		HashMap<Platform, HashMap<String, Object>> editRes = new HashMap<Platform, HashMap<String, Object>>();
		editRes.put(platform, reqData);
		parent.share(editRes);
		String toast = getContext().getString(R.string.sharing);
		Toast.makeText(getContext(), toast, 1).show();
//		finish();

	}

	public boolean handleMessage(Message msg) {
		checkAuthorization(platform);
		switch (msg.what) {
		case MSG_PLATFORM_LIST_GOT: {
			afterPlatformListGot();
		}
			break;
		case MSG_TOAST: {
			String text = actionToString(msg.arg1);
			Toast.makeText(getContext(), text, 0).show();
			btShare.setClickable(true);
		}
			break;
		}
		return false;
	}

	/** 显示平台列表 */
	public void afterPlatformListGot() {

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		int remain = MAX_TEXT_COUNT - etContent.length();
		tvCounter.setText(String.valueOf(remain));
		tvCounter.setTextColor(remain > 0 ? 0xffcfcfcf : 0xffff0000);
	}

	@Override
	public void afterTextChanged(Editable s) {

	}

	public void onResult(ArrayList<String> selected) {
		StringBuilder sb = new StringBuilder();
		for (String sel : selected) {
			sb.append('@').append(sel).append(' ');
		}
		etContent.append(sb.toString());
	}

	// 分享结果回调
	@Override
	public void onCancel(Platform plat, int action) {
		Message msg = new Message();
		Log.i(TAG, "" + action);

		if (action == Platform.ACTION_SHARE) {

			msg.what = MSG_TOAST;
			msg.arg1 = SHARE_CANCEL;
			UIHandler.sendMessage(msg, this);

		}
		if (action == Platform.ACTION_AUTHORIZING) {
			msg.what = MSG_TOAST;
			msg.arg1 = AUTHORE_CANCEL;
			UIHandler.sendMessage(msg, this);
		}

	}

	@Override
	public void onComplete(Platform plat, int action,
			HashMap<String, Object> arg2) {
		Log.i(TAG, "" + action);
		Message msg = new Message();
		if (action == Platform.ACTION_SHARE) {

			msg.what = MSG_TOAST;
			msg.arg1 = SHARE_SUCCESS;
			UIHandler.sendMessage(msg, this);
			new Ad().send(plat);
		}
		if (action == Platform.ACTION_AUTHORIZING) {
			msg.what = MSG_TOAST;
			msg.arg1 = AUTHORE_SUCCESS;
			UIHandler.sendMessage(msg, this);
		}
	}

	@Override
	public void onError(Platform plat, int action, Throwable t) {
		t.printStackTrace();
		Log.i(TAG, "" + action);
		// 解析数据成功，发送消息
		Message msg = new Message();
		if (action == Platform.ACTION_SHARE) {

			msg.what = MSG_TOAST;
			msg.arg1 = SHARE_FAILED;
			UIHandler.sendMessage(msg, this);
		}
		if (action == Platform.ACTION_AUTHORIZING) {
			msg.what = MSG_TOAST;
			msg.arg1 = AUTHORE_FAILED;
			UIHandler.sendMessage(msg, this);
		}

	}

	/** 将action转换为String */
	public String actionToString(int action) {
		switch (action) {

		case SHARE_SUCCESS:

			return getContext().getString(R.string.share_completed);
		case SHARE_FAILED:
			return getContext().getString(R.string.share_failed);
		case SHARE_CANCEL:
			return getContext().getString(R.string.share_canceled);
		case AUTHORE_SUCCESS:
			return getContext().getString(R.string.authore_completed);
		case AUTHORE_CANCEL:
			return getContext().getString(R.string.authore_canceled);
		case AUTHORE_FAILED:
			return getContext().getString(R.string.authore_failed);

		default: {
			return getContext().getString(R.string.unknow_error);
		}
		}
	}


}
